app.controller('servicingCtrl', function($scope, httpService, $timeout, toaster, $localStorage){
    $scope.searchParams = {};
    $scope.searchParams.label = "派发时间";
    $scope.count = 0;
    var url = "/servicing";
    $scope.MissionLevel = wtSys.Emun.MissionLevel; //紧急程度
    $scope.MissionMold = wtSys.Emun.MissionMold; //巡查类别
    $scope.MissionStatus = wtSys.Emun.MissionStatus; //任务状态
    $scope.TargetKind = wtSys.Emun.TargetKind; //目标种类
    $scope.MissionFromType = wtSys.Emun.MissionFromType; //来源类型
    $scope.DangerStatus = wtSys.Emun.DangerStatus; //隐患状态
    $scope.searchList = [{
        "typeId" : 1,
        "typeName" : "来源",
        "typeList" : [{"Id" : 2, "Name" : "隐患上报"}, {"Id" : 3, "Name" : "临时维修"}],
        // "isRadio":true,
    }, {
        "typeId" : 2,
        "typeName" : "状态",
        "typeList" : [{"Id" : 1, "Name" : "处理中", "checked" : true}, {
            "Id" : 2,
            "Name" : "待审核",
            "checked" : true
        }, {"Id" : 10, "Name" : "已完成"}, {
            "Id" : 11,
            "Name" : "已终止"
        }]
    }]; //搜索条件
    $scope.searchModel = [{"Id" : "1", "Name" : "处理中", "type" : "2"}, {"Id" : "2", "Name" : "待审核", "type" : "2"}];
    // 初始化查询变量
    $scope.initParam = function(){
        $scope.servicingList = [];
        $scope.page = 1;
        $scope.busy = false;
        $scope.limit = 10;
        $scope.isGetDetailTag = true; //第一次默认加载第一条记录右侧信息
    }
    $scope.edit = function(Id, index){
        // 还原表单以及表单值
        $scope.servicingForm.$setPristine();
        if(Id || Id == 0){
            $scope.id = Id;
            $scope.index = index;
            $scope.editModalTitle = "修改维护任务";
            $scope.getServicingDetail(Id);
        } else {
            $scope.id = null;
            $scope.index = null;
            $scope.servicingModel = {
                "MissionFromType" : 3,
                "MissionLevel" : null,
                "MissionMold" : null,
                "Note" : "",
                "Remark" : "",
                "HandlerId" : "",
                "Targets" : []
            }
            $scope.editModalTitle = "新增临时维修";
        }
        $('#editModal').modal('show');
    };
    //任务表单提交
    $scope.servicingFormSubmit = function(){
        $scope.servicingForm.$invalid = true;
        var path = url;
        var type = "POST";
        if($scope.id){
            path = url + "/" + $scope.id;
            type = "PUT";
        }
        httpService.request(type, path, $scope.servicingModel, function(result){
            $scope.servicingForm.$invalid = false;
            toaster.pop("success", "提示", result.message);
            $('#editModal').modal('hide');
            // 更新列表数据
            var arr = $scope.servicingList;
            if($scope.index != null && $scope.index >= 0){
                arr[$scope.index] = result.data; //index存在直接更新
                $scope.servicingDetailModel = angular.copy($scope.servicingModel); //更新右侧详情
            } else {
                arr.unshift(result.data);
                $scope.activeId = result.data.Id;
            }
            $scope.servicingList = arr;
        })
    }
    //删除任务弹框处理
    $scope.del = function(item, index){
        $scope.index = index;
        $scope.delModel = angular.copy(item);
        $('#delModal').modal('show');
    };
    //确认删除任务
    $scope.delConfirm = function(){
        $('#delModal').modal('hide');
        var path = url + '/' + $scope.delModel.Id;
        httpService.request("DELETE", path, null, function(result){
            toaster.pop("success", "提示", result.message);
            // 更新列表数据
            var arr = $scope.servicingList;
            arr.splice($scope.index, 1);
            $scope.servicingModelList = arr;
            //如果删除的是第一条数据,删除成功后重新设置activeId的值
            if($scope.index == 0){
                $scope.activeId = arr[0] ? arr[0].Id : null;
            }
        });
    }
    //展示来源编号详情
    $scope.detail = function(detailId){
        $('#detailModal').modal('show');
        $scope.getDangerDetail(detailId);
    }
    //获取隐患详细信息
    $scope.getDangerDetail = function(targetId){
        var path = '/danger/' + targetId;
        httpService.request("GET", path, null, function(result){
            $scope.dangerDetailModel = result.data;
        });
    }
    //获取任务详情
    $scope.getServicingDetail = function(Id, isRgt){
        var path = url + '/' + Id;
        httpService.request("GET", path, null, function(result){
            if(isRgt){
                $scope.servicingDetailModel = result.data;
                if($scope.servicingDetailModel.MissionFromType == 2 && $scope.servicingDetailModel.Items && $scope.servicingDetailModel.Items.length > 0){
                    $scope.getDangerDetail($scope.servicingDetailModel.Items[0].TargetId);
                }
            } else {
                $scope.servicingModel = result.data;
            }
            // 设置当前定位点
            var _data = result.data;
            $scope.servicingDetailModel.currentPosion = [];//清空当前位置信息
            if(_data.Items && _data.Items.length > 0){

                _data.Items.forEach(function(item){
                    $scope.servicingDetailModel.currentPosion.push({x : item.TargetLng, y : item.TargetLat});
                });
            }
            delete  _data;//手动删除_data
        });
    }
    //获取维修反馈
    $scope.getFeedbackList = function(Id){
        var path = url + '/FeedbackList/' + Id;
        httpService.request("GET", path, null, function(result){
            $scope.feedbackList = result.data;
        });
    }
    //获取任务列表
    $scope.getServicingList = function(isSearch){
        if(isSearch){
            $scope.initParam();
        }
        if($scope.busy) return false;
        var missionstatus = "";//状态
        var missionfromtype = "" //来源
        var key = $scope.key ? $scope.key : "";
        if($scope.searchModel){
            var arr = $scope.searchModel;
            if(arr.length > 0){
                var missionstatusArr = [];
                var missionfromtypeArr = [];
                arr.forEach(function(item, index){
                    if(item.type == 1){
                        missionfromtypeArr.push(item.Id);
                    } else {
                        missionstatusArr.push(item.Id);
                    }
                });
                missionstatus = missionstatusArr.join(",");
                missionfromtype = missionfromtypeArr.join(",");
            }
        }
        var begintime = $scope.searchParams.begintime;
        begintime = begintime ? moment(begintime).format("YYYY-MM-DD") : "";
        var endtime = $scope.searchParams.endtime;
        endtime = endtime ? moment(endtime).format("YYYY-MM-DD") : "";
        var path = url + '?page=' + $scope.page + '&limit=' + $scope.limit + '&filter=key:' + key + ";missionstatus:" + missionstatus + ";missionfromtype:" + missionfromtype + ";begintime:" + begintime + ";endtime:" + endtime;
        $scope.busy = true;
        httpService.request("GET", path, null, function(result){
            $scope.count = result.count;
            //$scope.deviceList = result.data;
            if(!result.success){
                toaster.error(result.message);
            }
            angular.forEach(result.data, function(data, i){
                $scope.servicingList.push(data);
            });
            if(result.data.length >= $scope.limit){
                $scope.busy = false;
                $scope.page += 1;
            }
            //搜索结果为空 将activeId置为空
            if($scope.servicingList.length == 0){
                $scope.activeId = null;
                return
            }
            if($scope.servicingList.length > 0 && $scope.isGetDetailTag){
                $scope.isGetDetailTag = false;
                var arr = $scope.servicingList;
                $scope.activeId = arr[0].Id; //默认查询第一条记录的详情
            }
        });
    }

    //获取用户列表
    $scope.getUserList = function(){
        var path = '/user?page=1';
        httpService.request("GET", path, null, function(result){
            $scope.userList = result.data;
        });
    }
    //获取右侧model
    $scope.getRgtModel = function(){
        //点击列表重置查询参数
        if(!$scope.activeId){
            return
        }
        $scope.getServicingDetail($scope.activeId, true); //获取维护任务详情
        $scope.getFeedbackList($scope.activeId);
    }
    /*业务类*/
    //派发任务
    /*$scope.mission=function(item){
     var path="/mission/push/"+item.Id;
     httpService.request("put", path, {HandlerId:item.HandlerId}, function(result){
     toaster.pop("success", "提示", result.message);
     }
     )
     }*/
    //终止维修任务
    $scope.servicingStop = function(item, statu){
        if(item.MissionStatus == 10 || item.MissionStatus == 11){
            return
        }
        var path = url + "/ServicingStop";
        httpService.request("put", path, {
            "Id" : item.Id
        }, function(result){
            toaster.pop("success", "提示", result.message);
            item.MissionStatus = statu;//改变左边列表状态
            var arr = $scope.feedbackList;
            if(arr.length > 0){
                arr[0].MissionStatus = statu;//改变右边列表状态
            }
            $scope.servicingDetailModel.MissionStatus = statu;//改变详情状态
        })
    }
    //审核
    $scope.audit = function(feedback){
        var path = url + "/audit";
        var tag = feedback.MissionStatus == 10 ? true : false; //是否审核成功
        httpService.request("put", path, {
            "Id" : feedback.MissionDetailId,
            "isAudit" : tag
        }, function(result){
            toaster.pop("success", "提示", result.message);
            $scope.getRgtModel()//重新更新右边信息
            var newArr = _.filter($scope.servicingList, function(n){
                if(n.Id == feedback.Id){
                    n.MissionStatus = feedback.MissionStatus;
                    return
                }
            });
        })
    }
    /**
     * 任务定位操作
     * @param id 传入设施id
     *
     */
    $scope.location = function(id){

    }
    //地图高度
    $scope.mapheight = 400;

    $scope.mapIntialed = function($scope){

        //初始化地图操作对象(基于此对象操作地图元素)
        var mapobj = $scope.$$childHead.mapinstance;


        mapobj.addDynamicMap($rootScope.arcgisConfig.baseMap);

        mapobj.addFeatureLayer("设备点", {
            maxScale : 0, minScale : 0, showInfoTemplate : false,
            definitionExpression : "unitid=" + $localStorage.userInfo.unitid
        });

    };

    //地图多点选择
    $scope.setLocationOption = {
        mapid : "setLocation",
        center : {x : 155307.451, y : 139762.144, lng : 0, lat : 0},
        zoom : 3,
        height : 600,
        showgdmap : false,
        layers : [{layerName : "隐患点", layerFilter : "unitid=" + $localStorage.userInfo.unitid},
            {layerName : "设备点", layerFilter : "unitid=" + $localStorage.userInfo.unitid}]
    };

    $scope.initParam(); // 初始化查询列表变量
    $scope.getServicingList(); //获取任务列表
    $scope.getUserList(); //获取用户列表
});
